package com.bawei.work_manager;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.work.BackoffPolicy;
import androidx.work.Constraints;
import androidx.work.Data;
import androidx.work.NetworkType;
import androidx.work.OneTimeWorkRequest;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkContinuation;
import androidx.work.WorkInfo;
import androidx.work.WorkManager;
import androidx.work.Worker;

import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/***
 * WorkManager:省电的异步后台任务
 * 1。特点
 * （1）保证任务一定完成，即可退出应用或重起设备(任务信息存储到数据库,持久化存储)
 * （2）针对不需要及时完成任务处理
 * （3）兼容范围广，API 14以上所有手机，
 * 2。使用
 *
 */
public class MainActivity extends AppCompatActivity {
    private OneTimeWorkRequest workRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //任务触发条件,以NetWorkType为
        //NetworkType.NOT REQUIRED: 对网络没有要求
        //NetworkType.CONNECTED: 网络连接的时候执行
        //NetworkType.UNMETERED:环计费的网络比如WIFI下执行
        //NetworkType.NOT ROAMING:非漫游网络状态执行
        //NetworkType.METERED: 计费网络比如3G，4G下执行
        Constraints constraints = new Constraints.Builder()
//                .setRequiredNetworkType(NetworkType.UNMETERED)//WIFI
//                .setRequiresBatteryNotLow(true)//低电量不能执行
//                .setRequiresCharging(true)//充电状态才能执行
//                .setRequiresDeviceIdle(true)//空闲的时候才能执行
//                .setRequiresStorageNotLow(true)//内存充足的时候才能执行
                .build();
        //创建输入数据
        Data data = new Data.Builder()
                .putString("username", "占三")
                .putInt("age", 19)
                .build();
        //一次性任务请求
        workRequest = new OneTimeWorkRequest.Builder(MyWork.class)
                .setConstraints(constraints)//设置触发条件
                .setInitialDelay(5, TimeUnit.SECONDS)//设置延迟
                .addTag("work1")//设置标签，当多个任务的时候通过标签获得对应的任务
                //设置退避策略  LINEAR重试间隔时间 12 24 36 不能低于10秒，不能超过5小时
                .setBackoffCriteria(BackoffPolicy.LINEAR,12,TimeUnit.SECONDS)
                .setInputData(data)//设置输入参数
                .build();
        //观察任务的状态:LiveData可观察的数据类
        WorkManager.getInstance(this).getWorkInfoByIdLiveData(workRequest.getId())
                .observe(this, new Observer<WorkInfo>() {
                    @Override
                    public void onChanged(WorkInfo workInfo) {
                        Log.d("ytx", "workInfo: "+workInfo);

                        if(workInfo != null && workInfo.getState() == WorkInfo.State.SUCCEEDED){
                            Data outputData = workInfo.getOutputData();
                            String info = outputData.getString("info");
                            Log.d("ytx", "任务执行后的结果: "+info);
                        }
                    }
                });
    }

    //将任务请求交给WorkManager执行
    @RequiresApi(api = Build.VERSION_CODES.M)
    public void start(View view) {
        WorkManager.getInstance(this).enqueue(workRequest);

    }
    //取消任务
    public void cancel(View view) {
        WorkManager.getInstance(this).cancelAllWorkByTag("work1");
    }
    //启动周期任务
    public void startPeriodic(View view) {
        //周期任务，每隔1小时执行一次,不能小于15分钟
        PeriodicWorkRequest periodicWorkRequest = new PeriodicWorkRequest.Builder(MyWork.class, 1, TimeUnit.HOURS)
                .build();
        WorkManager.getInstance(this).enqueue(periodicWorkRequest);


    }
    //任务链
    public void startLian(View view) {
        OneTimeWorkRequest a = new OneTimeWorkRequest.Builder(AWork.class)
                .build();
        OneTimeWorkRequest b = new OneTimeWorkRequest.Builder(BWork.class)
                .build();
        WorkManager.getInstance(this)
                .beginWith(a)
                .then(b)
                .enqueue();


    }
    //任务组合 ：（a-》B）（ c-》D）  --》e
    public void startContinuation(View view) {
        OneTimeWorkRequest a = new OneTimeWorkRequest.Builder(AWork.class)
                .build();
        OneTimeWorkRequest b = new OneTimeWorkRequest.Builder(BWork.class)
                .build();
        OneTimeWorkRequest c = new OneTimeWorkRequest.Builder(CWork.class)
                .build();
        OneTimeWorkRequest d = new OneTimeWorkRequest.Builder(DWork.class)
                .build();
        OneTimeWorkRequest e = new OneTimeWorkRequest.Builder(EWork.class)
                .build();

        //a-》B
        WorkContinuation continuationAB = WorkManager.getInstance(this)
                .beginWith(a)
                .then(b);
        //c->d
        WorkContinuation continuationCD = WorkManager.getInstance(this)
                .beginWith(c)
                .then(d);
        //放在集合中
        List<WorkContinuation> list = new ArrayList<>();
        list.add(continuationAB);
        list.add(continuationCD);
        //执行
        WorkContinuation.combine(list)
                .then(e)
                .enqueue();
    }
}